import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import moment from "moment";
import { Row, Col, Card, Icon, Button, Popconfirm, message, Divider, Form, Select, Input} from "antd";
import RegionalSelection from "../../Form/RegionalSelection";
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';


const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');


@connect(({ energy, loading }) => ({
  resdata: energy.resdata,
  loading: energy.loading.reslist,
}))
@Form.create()
export default class EnergyHistory extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {

    const { pageSize } = this.state;
    const { location,dispatch } = this.props;
    const pagesquery = location.query;

    // 获取区域数据
    dispatch({
      type: 'global/fetch_select_district',
    })

    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }


  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if (nextProps.isReloadList === true && this.props.isReloadList === false) {
      const { pageSize } = this.state;
      this.getDataList({},pageSize,1);
      this.props.sotpReloadList();
    }
  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch,location } = this.props;
      dispatch({
        type: 'energy/fetch_burglarproof_list',
        payload: {
          pageSize,
          currentPage,
          ...params,
          region:undefined,
        },
      });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    this.setState({
      formValues: {},
    });
    form.resetFields();
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.warnId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.region && fieldsValue.region.districtId.length>0){
        fieldsValue.districtId = fieldsValue.region.districtId[fieldsValue.region.districtId.length - 1];
      }
      if(fieldsValue.region && fieldsValue.region.pointId!==0 && fieldsValue.region.districtId.length>0){
        fieldsValue.pointId = fieldsValue.region.pointId;
      }

      fieldsValue.region = undefined;

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };


  // 安装点位事件
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }

  }

  // 导出
  handleActionExport = () => {

    const { dispatch } = this.props;
    const { formValues } = this.state;

    dispatch({
      type: 'energy/action_burglarproof_export',
      payload: {
        ...formValues,
      },
    }).then(()=>{
      message.success("防盗信息已导出")
    })
  };


  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource,location } = this.props;
    const { getFieldDecorator } = form;
    const pagesquery = location.query;

    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="设备名称">
              {getFieldDecorator('devName',{
                initialValue: pagesquery && pagesquery.devName ? pagesquery.devName : undefined,
              })(<Input placeholder="请输入设备名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="设备类型">
              {getFieldDecorator('devType',{
                initialValue: pagesquery && pagesquery.devType ? pagesquery.devType : undefined,
              })(
                <Select allowClear={true} placeholder="请选择设备类型" style={{ width: '100%' }}>
                  {dictionaries.deviceType && dictionaries.deviceType.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="区域点位">
              {getFieldDecorator('region',{
                initialValue: pagesquery && pagesquery.region ? pagesquery.region : {districtId:[],pointId:0},
              })(
                <RegionalSelection
                  districtData={selectSource.districtData}
                  pointData={selectSource.pointData}
                  onChange={this.handleSearchDistrict}
                />
              )}
            </FormItem>
          </Col>

          <Col md={4} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, dictionaries } = this.props;
    const { selectedRows } = this.state;
    const burglarproofStatus = dictionaries.burglarproofStatus && dictionaries.burglarproofStatus.length>1
      ? dictionaries.burglarproofStatus.map(item=>item.label)
      :[];

    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        align:'center',
        render: (text, row, index)=> (
          <span>{index+1}</span>
        ),
      },
      {
        title: '区域',
        dataIndex: 'districtName',
      },
      {
        title: '设备名称',
        dataIndex: 'devName',
      },
      {
        title: '防盗信息',
        dataIndex: 'burglarproofStatus',
        render: (text)=> (
          <span>{burglarproofStatus[parseInt(text)-1]}</span>
        ),
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },

    ];




    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
  {/*        <div className={styles.tableListOperator}>
            <Authorized authority={'10062'} >
              <Button type="default"
                      onClick={() => this.handleActionExport()}
               >
                导出
              </Button>
            </Authorized>

          </div>*/}
          <StandardTable
            rowKey="devId"
            loading={loading}
            data={resdata}
            columns={columns}
            selectedRows={selectedRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
